
use gfsc::*;
use ansi_term::Colour;
use clap::Parser;
use dirs::home_dir;

#[derive(Parser, Debug)]
#[clap(
    name = "gfs serarch",
    version,
    author,
    about = "search from gfs"
)]
struct Cli {
    /// 
    #[clap(name = "query",  default_value = "")]    
    query: String,
    /// Sets a type
    #[clap(name = "type", short, long, default_value = "")]    
    r#type: String,
    /// Sets a router.json
    #[clap(name = "router", short, long, default_value = "~/.rabbit/router.json")]    
    router: String,
}

pub fn main() {

    let mut cli = Cli::parse();
    if cli.router.as_str().eq("~/.rabbit/router.json"){        
        let home =  home_dir().unwrap();
        cli.router = home.join(".rabbit").join("router.json").display().to_string();
    }
 
    let router = gfsc_new_router( &cli.router ).unwrap();    
    let para = SearchParams { page: 1, q: cli.query,  t:cli.r#type   };
    let f = gfsc_search(&router , router.cur_dynasty, &para);
    let rt = tokio::runtime::Runtime::new().unwrap();
    let r = rt.block_on(f).unwrap();
    
    if r.len() == 0 {
        println!("search result = {}", Colour::Red.paint("0") );
    }
    for i in 0..r.len() {       
        let doc = &r[i];
        let s = &doc.content;
        let nc = s.replace("<mark>" , Colour::Red.prefix().to_string().as_str());
        let nc =  nc.replace("</mark>" , Colour::Red.suffix().to_string().as_str());

//        let f1 = s.find("<mark>").unwrap();
  //      let f2 = s.find("</mark>").unwrap();
    //    let ss = format!("{}{}{}", &s.as_str()[0..f1], Colour::Red.paint(&s.as_str()[f1+6..f2]), &s.as_str()[f2+7..]  );        
        println!("{}\n\t{}", doc.fname, nc);

    }

}
 